package com.sddz.pacs.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.sddz.pacs.entity.SysUser;
import com.sddz.pacs.entity.SysUserRole;
import com.sddz.pacs.mapper.SysUserRoleMapper;
import com.sddz.pacs.service.SysUserRoleService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.sddz.pacs.util.ShiroUtils;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 系统用户角色表 服务实现类
 * </p>
 *
 * @author 时代电子
 * @since 2018-05-16
 */
@Service
public class SysUserRoleServiceImpl extends ServiceImpl<SysUserRoleMapper, SysUserRole> implements SysUserRoleService {

    @Override
    public boolean addSysUserRole(SysUser sysUser) {

        String userId = sysUser.getId();
        List<String> roleIdList = sysUser.getRoleIdList();
        if (roleIdList.size()>0){
            for (String roleId : roleIdList){
                SysUserRole sysUserRole = new SysUserRole();
                sysUserRole.setRoleId(roleId);
                sysUserRole.setUserId(userId);
                sysUserRole.setUpdateUserid(ShiroUtils.getUserId());
                sysUserRole.setCreateUserid(ShiroUtils.getUserId());

                int result = this.baseMapper.insert(sysUserRole);
                if (result>0){
                    return false;
                }
            }
        }
        return true;
    }

    /**
     * 更新操作
     * @param sysUser
     * @return
     */
    @Override
    public boolean updateUserRole(SysUser sysUser) {
        //删除人员对应的角色
        Map map = new HashMap();
        map.put("USER_ID",sysUser.getId());
        this.baseMapper.deleteByMap(map);

        //删除后重新添加
        String userId = sysUser.getId();
        List<String> roleIdList = sysUser.getRoleIdList();
        if (roleIdList.size()>0){
            for (String roleId : roleIdList){
                SysUserRole sysUserRole = new SysUserRole();
                sysUserRole.setRoleId(roleId);
                sysUserRole.setUpdateUserid(userId);
                sysUserRole.setUserId(ShiroUtils.getUserId());
                sysUserRole.setUpdateUserid(ShiroUtils.getUserId());

                int result = this.baseMapper.insert(sysUserRole);
                if (result>0){
                    return false;
                }
            }
        }
        return true;
    }

    //根据人员id获取角色id数组
    @Override
    public List<String> getRoleIdList(String userId) {
        EntityWrapper<SysUserRole> ew = new EntityWrapper<>();
        //添加条件校验
        ew.eq("USER_ID",userId);
        List<String> sysUserRoles = this.baseMapper.getRoleIdList(ew);

        return sysUserRoles;
    }
}
